package com.manage.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.manage.common.lang.Result;
import com.manage.entity.Pickup;
import com.manage.entity.vo.PieEchartsRes;
import com.manage.service.IPickupService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 领取教材
 */
@RestController
@RequestMapping("/pickup")
public class PickupController {
    @Autowired
    IPickupService pickupService;
    @GetMapping("/list")
    public Result list(@PathParam("current") Integer current, @PathParam("size") Integer size){
        Page<Pickup> page = pickupService.selectListByPage(current, size);
        return Result.success(page);
    }
    //添加数据
    @PostMapping("add")
    public Result save(@Validated @RequestBody Pickup pickup){
        LocalDateTime date=LocalDateTime.now();
        pickup.setCreateTime(date);
        pickupService.savePickup(pickup);
        return Result.success("添加成功");
    }

    //更新单条数据,实体传入id,不能更改创建时间
    @PostMapping("/update")
    public Result update(@Validated @RequestBody Pickup pickup){
        UpdateWrapper<Pickup> pickupUpdateWrapper = new UpdateWrapper<Pickup>();
        pickupUpdateWrapper.eq("id",pickup.getId());
        pickupService.update(pickup,pickupUpdateWrapper);
        return Result.success("更新成功") ;
    }

    //删除单个，参数id
    @RequiresAuthentication
    @GetMapping("/delete")
    public Result delete(@PathParam("id") Integer id){
        Pickup pickup = pickupService.getById(id);
        Assert.notNull(pickup, "该教材已删除");
        pickupService.deleteById(id);
        return Result.success("删除成功");
    }

    @RequiresAuthentication
    //删除所有，参数：字符串数组
    @PostMapping("/deleteAll")
    public Result deleteAll(@RequestBody String[] idList ){
        return Result.success( pickupService.removeByIds(Arrays.asList(idList))) ;
    }

    //条件查询
    @PostMapping("/query")
    public Result query(@RequestBody Pickup pickup ){
        List<Pickup> pickupList = pickupService.queryByCondition(pickup);
        return Result.success( pickupList) ;
    }

    /**
     * 统计各个教材的领取数量
     * @return
     */
    @GetMapping("/count")
    public Result count() {
        List<PieEchartsRes> list =  pickupService.countForEcharts();
        return Result.success(list);
    }
}
